using System;
using System.Diagnostics;

namespace nTribeHR.Utilities
{
    public class DisposableStopwatch : Stopwatch, IDisposable
    {
        public string Name { get; set; }
        public new static DisposableStopwatch StartNew()
        {
            System.Diagnostics.StackTrace st = new StackTrace();
            if( st.FrameCount > 2)
            {
                return StartNew(st.GetFrame(1).GetMethod().Name);
            }
            return StartNew(string.Empty);
        }

        public static DisposableStopwatch StartNew(string name)
        {
            var result = new DisposableStopwatch(){Name = name};
            result.Start();
            return result;
        }

        public override string ToString()
        {
            return string.Format("{0} : {1:#,##0} ms", Name, ElapsedMilliseconds);
        }

        #region Implementation of IDisposable

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            if( IsRunning)  
                Stop();
        }

        #endregion
    }
}